package cn.tedu.micro.demo.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;

/**
 * 测试自定义路由交换机和队列的绑定关系
 */
@Slf4j
public class MyDirectProducer {
    private Channel channel;
    /**
     * @Before注解 junit提供的功能 作用是在所有@Test方法执行之前 执行,一般是初始化功能
     */
    @Before
    public void createChannel(){
        try{
            //1.创建连接工厂-工厂模式 创建连接的过程 被工厂封装了
            ConnectionFactory factory = new ConnectionFactory();
            //2.给工厂提供连接创建的必要属性
            //2.1rabbitmq host
            factory.setHost("192.168.8.100");
            //2.2rabbitmq port
            factory.setPort(5672);
            //2.3账号权限
            factory.setUsername("admin");
            factory.setPassword("123456");
            //3.生成一个长连接
            Connection connection = factory.newConnection();
            //4.创建通道短链接
            channel = connection.createChannel();
        }catch (Exception e){
            log.error("创建连接失败");
        }
    }
    //测试多个队列声明
    //声明一个 自定义路由交换机
    //将队列按照 自定义路由key绑定给交换机
    @Test
    public void declareBinding(){

        try{
            //1.声明2个队列 queue01 queue02
            channel.queueDeclare("queue01",false,false,false,null);
            channel.queueDeclare("queue02",false,false,false,null);
            //2.声明 自定义路由交换机 direct_ex  direct fanout topic header
            channel.exchangeDeclare("direct_ex","direct");
            //3.将声明创建的队列 绑定给交换机 queue01--北京  queue02--上海
            channel.queueBind("queue01","direct_ex","北京");
            channel.queueBind("queue02","direct_ex","上海");
            //注意 绑定关系可以N:N
        }catch (Exception e){
            log.error("创建队列失败",e);
        }
    }
    @Test
    public void declareTestBinding(){

        try{
            //1.声明2个队列 queue01 queue02
            channel.queueDeclare("queueA",false,false,false,null);
            channel.queueDeclare("queueB",false,false,false,null);
            channel.queueDeclare("queueC",false,false,false,null);
            //2.声明 自定义路由交换机 direct_ex  direct fanout topic header
            channel.exchangeDeclare("direct_test_ex","direct");
            //3.将声明创建的队列 绑定给交换机 queue01--北京  queue02--上海
            channel.queueBind("queueA","direct_test_ex","北京");
            channel.queueBind("queueA","direct_test_ex","上海");
            channel.queueBind("queueB","direct_test_ex","上海");
            channel.queueBind("queueB","direct_test_ex","广州");
            channel.queueBind("queueC","direct_test_ex","重庆");
            channel.queueBind("queueC","direct_test_ex","广州");
            //注意 绑定关系可以N:N
        }catch (Exception e){
            log.error("创建队列失败",e);
        }
    }
}
